package org.unisinos.gc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.unisinos.gc.vo.Artigo;
import org.unisinos.gc.vo.SubArea;

public class CoautorDAO {

	public static String[] getCoautoresByArtigo(int codigo) throws SQLException {
		List<String> codAutores = new ArrayList<String>();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConnectionManager.getConnection();
			stmt = con.prepareStatement("select * from coautor where cod_artigo = ?");
			stmt.setInt(1, codigo);
			rs = stmt.executeQuery();
			while(rs.next()) {
				codAutores.add(String.valueOf(rs.getInt("cod_autor")));
			}
		} finally {
			try {
				if (con!=null)con.close();
				if (stmt!=null)stmt.close();
				if (rs!=null)rs.close();
			}catch (Exception e) {}
		}
		return codAutores.toArray(new String[codAutores.size()]);
	}
	
	public static void updateCoautoresByArtigo(int codArtigo, String[] codAutores) throws SQLException {
		deleteByArtigo(codArtigo);
		for (String string : codAutores) {
			int codAutor = Integer.parseInt(string);
			addCoautor(codArtigo, codAutor);
		}
	}
	
	public static void addCoautor(int codArtigo, int codAutor) throws SQLException {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionManager.getConnection();
			ps = con.prepareStatement("INSERT INTO coautor(cod_artigo, cod_autor) " +
					"VALUES (?, ?)");
			ps.setInt(1, codArtigo);
			ps.setInt(2, codAutor);
			ps.executeUpdate();
		} finally {
			try {
				if (con!=null)con.close();
				if (ps!=null)ps.close();
			}catch (Exception e) {}
		}
	}
	
	public static void deleteByArtigo(int codigo) throws SQLException {
		Connection con = null;
		PreparedStatement ps = null;
		try {
			con = ConnectionManager.getConnection();
			ps = con.prepareStatement("delete from coautor where cod_artigo = ?");
			ps.setInt(1, codigo);
			ps.executeUpdate();
		} finally {
			try {
				if (con!=null)con.close();
				if (ps!=null)ps.close();
			}catch (Exception e) {}
		}
	}
	
}